package cn.wolfcode.luowowo.website.web.interceptor;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.cache.util.RedisKeys;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.web.util.CookiesUtil;
import cn.wolfcode.luowowo.website.web.annotation.RequireLogin;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckLoginInterceptor implements HandlerInterceptor {
    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = CookiesUtil.getCookie(request, response, "token",RedisKeys.USER_LOGIN_TOKEN.getTime().intValue());
        UserInfo user = userInfoRedisService.getUserLoginToken(token);
        if (handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //如果访问的资源有贴需要登录的注解
            if (handlerMethod.hasMethodAnnotation(RequireLogin.class)){
                if(user == null){
                    response.sendRedirect("/login.html");
                    return false;
                }
            }
        }
        request.getSession().setAttribute("userInfo",user);
        return true;
    }
}
